<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/1/7 0007
 * Time: 下午 7:19
 */

namespace app\admin\controller;

use app\admin\model\UserModel;
use think\facade\Cookie;
use think\Request;

class User extends Base
{
    public function initialize()
    {
        $userId = Cookie::get("userId");
        if (empty($userId)) {
            $this->success("您还未登入，请您先登入",url('/admin/login/login'),"",1);
        }
        $result = (new UserModel())->get($userId)->role()->field("id")->find();
        if (!in_array($result["id"],["1"]) ) {
            $this->error("页面不存在",url("admin/index/error403"),"",1);
        }
    }

    /**
     * 用户管理
     * @return mixed
     */
    public function index()
    {
        return $this->fetch();
    }

    public function getUserAll(Request $request)
    {

        if ($request->isAjax()) {
            $page = $request->param("page");
            $limit = $request->param("limit");

            $model = new UserModel();
            $result = $model
                ->order("create_time","DESC")
                ->paginate($limit);

//            $user = User::get(1);
//// 获取用户的所有角色
//            $roles = $user->roles;
//            foreach ($roles as $role) {
//                // 输出用户的角色名
//                echo $role->name;
//                // 获取中间表模型
//                dump($role->pivot);
//            }

            foreach ($result as $key => $value) {
                $result[$key]["role"] = $value->role()->find()["name"];
            }

            return json(["code" => 0, "msg" => "ok","count" => $result->total() ,"data" => $result->items()]);
        }
    }
}